package groovy.etl

import groovy.xml.MarkupBuilder
import org.w3c.dom.Document
import org.xml.sax.InputSource
import scriptella.configuration.ConfigurationEl
import scriptella.configuration.ConfigurationFactory
import scriptella.configuration.XmlElement
import scriptella.execution.EtlExecutor
import scriptella.expression.PropertiesSubstitutor
import scriptella.spi.support.HierarchicalParametersCallback
import scriptella.spi.support.NullParametersCallback

import javax.xml.parsers.DocumentBuilder
import scriptella.interactive.ConsoleProgressIndicator

/**
 * Created with IntelliJ IDEA.
 * User: tbarker
 * Date: 4/27/12
 * Time: 10:12 PM
 * To change this template use File | Settings | File Templates.
 */
class EtlRunner {

    def run(Closure closure) {
        def writer = new StringWriter()
        def xml = new MarkupBuilder(writer)
        xml.etl(closure)
        def properties = System.getProperties()
        DocumentBuilder db = ConfigurationFactory.DBF.newDocumentBuilder();
        db.setEntityResolver(ConfigurationFactory.ETL_ENTITY_RESOLVER);
        db.setErrorHandler(ConfigurationFactory.ETL_ERROR_HANDLER);
        def xmlText = writer.toString()
        def bytes = xmlText.getBytes("utf-8")

        final InputSource inputSource = new InputSource(new ByteArrayInputStream(bytes));
        final Document document = db.parse(inputSource);
        HierarchicalParametersCallback params = new HierarchicalParametersCallback(
            NullParametersCallback.INSTANCE, null);
        PropertiesSubstitutor ps = new PropertiesSubstitutor(params);

        def configuration = new ConfigurationEl(new XmlElement(
            document.getDocumentElement(), null, ps), params);
        def etlExecutor = new EtlExecutor()
        etlExecutor.setConfiguration(configuration)
        ConsoleProgressIndicator indicator = new ConsoleProgressIndicator("Execution Progress");
        def statistics = etlExecutor.execute(indicator)
        println "Execution statistics:\n" + statistics.toString()
    }


}
